package tech.abing.spider.task.pageprocessor.sumuwang;

import java.util.List;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import tech.abing.spider.component.PageProcessor;
import tech.abing.spider.component.PageScript;
import tech.abing.spider.model.Proccessable;
import tech.abing.spider.page.OkPage;
import tech.abing.spider.page.Page;
import tech.abing.spider.request.BasicRequest;
import tech.abing.spider.request.PageRequest;
import tech.abing.spider.request.StartContext;
import tech.abing.spider.task.model.sumuwang.FundDataEntity;
import tech.abing.spider.task.pageprocessor.amac.ManagerProcessor;
import tech.abing.spider.util.DateUtils;
import tech.abing.spider.util.StringUtils;

public class FundDataProcessor implements PageProcessor {

	static Pattern normalContain = Pattern.compile("pager");// 正常页面必定会存在的字符，你也可以使用页面上其他的字符
	private static Logger logger = Logger.getLogger(FundDataProcessor.class);

	@Override
	public PageScript getJavaScript() {
		return null;
	}

	@Override
	public Pattern getNormalContain() {
		return normalContain;
	}

	@Override
	public void process(OkPage page, StartContext context,
			List<BasicRequest> queue, List<Proccessable> objectContainer)
			throws Exception {

		JSONObject jsonObj = JSONObject.fromObject(page.getContent());

		JSONArray jsonArr = jsonObj.getJSONArray("data");
		if (jsonArr != null && jsonArr.size() > 0) {

			JSONObject json = jsonArr.getJSONObject(0);// 最多一条
			// 解析数据
			FundDataEntity fundData = new FundDataEntity();
			fundData.setAdvisorId(json.getString("advisor_id"));
			fundData.setCompanyName(json.getString("company_name"));
			fundData.setFundId(json.getString("fund_id"));
			fundData.setFundShortName(json.getString("fund_short_name"));
			fundData.setId(json.getString("id"));
			fundData.setInceptionDate(DateUtils.parseDate(
					json.getString("inception_date"),
					new String[] { "yyyy-MM-dd" }));
			fundData.setInitialUnitValue(json.getDouble("initial_unit_value"));
			fundData.setManagerId(json.getString("manager_id"));
			fundData.setManagerName(json.getString("manager_name"));
			fundData.setNav(json.getDouble("nav"));
			fundData.setPriceDate(DateUtils.parseDate(
					json.getString("price_date"), new String[] { "yyyy-MM-dd" }));
			fundData.setRetIncep(json.getDouble("ret_incep"));
			if (json.get("ret_incep_a") != null
					&& !"null".equals(json.get("ret_incep_a").toString())) {
				fundData.setRetIncepA(json.getDouble("ret_incep_a"));
			}
			fundData.setRetInception(json.getDouble("ret_inception"));
			StringUtils.removeSpace(fundData);
			objectContainer.add(fundData);

			// 处理跟进队列
			String url = "http://dc.simuwang.com/Fund/getNavHis.html?id="
					+ fundData.getFundId() + "&page=1&json=1";
			PageRequest request = context.createPageRequest(url,
					FundNavProcessor.class);
			request.getExtParams().put("fundId", fundData.getFundId());

			request.putHeader(
					"Cookie",
					"guest_id=1481883047; regsms=1481882878000; smppw_tz_auth=1; had_quiz_281090=1481882928000; PHPSESSID=3veq5avmupr1nibejqhtfd5r04; rz_token_6658=f800ad08789d0b26cc438d2bc83049bb.1481941519; stat_sessid=jb5e5gcrajm6v1hr8bu3qhgmq5; http_tK_cache=175d9e275bba231e2a097279543e4d4fbe1cfd51; cur_ck_time=1481941520; ck_request_key=IwEY6lyDRRH%2BCOaU1DvRVfvoEkMIdxJEUz45ymAuhG4%3D; passport=281090%09u_476668644256%09VlVQClFTB18BUVAFVVAFVw1WAQcDVQJUBwYBAgUFBVY%3D1b38ea2618; rz_u_p=d41d8cd98f00b204e9800998ecf8427e%3Du_476668644256; rz_rem_u_p=ip7zS1Cvi24LS6tsm%2F%2BasobNd9Bwrq0y5DuZAJclD9A%3D%24zxIAAybf1yufdhQt6M1IKEUQhYg0VrGymP%2BaSvbTukM%3D; passportmall=A1pXBAVRaBNmAQNSUAFZVVFXVAYP7378cf9565; autologin_status=1; fyr_ssid_n5776=fyr_n5776_iwslpudx; Hm_lvt_c3f6328a1a952e922e996c667234cdae=1481882878,1481941519; Hm_lpvt_c3f6328a1a952e922e996c667234cdae=1481941674");
			request.putHeader("Content-Type", "application/json; charset=UTF-8");
			request.putHeader(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36");
			request.putHeader("Accept",
					"application/json, text/javascript, */*; q=0.01");
			request.putHeader("Accept-Language", "zh-CN,zh;q=0.8");
			request.putHeader("Cache-Control", "no-cache");

			request.putHeader("Referer", "http://dc.simuwang.com/product/"
					+ fundData.getFundId() + ".html");

			request.putHeader("X-Requested-With", "XMLHttpRequest");
			request.putHeader("Host", "dc.simuwang.com");

			queue.add(request);
		} else {
			logger.info("请求:" + page.getRequest().getUrl() + ",未检索到数据!");
		}

	}

	@Override
	public void processErrorPage(Page page, StartContext context,
			List<Proccessable> objectContainer) throws Exception {
		// TODO Auto-generated method stub

	}

}
